import axios from "axios";
import { useUserStore } from "@/stores";
// import { ElMessage } from "element-plus";
import router from '@/router/index'


const instance = axios.create({
  // baseURL: 'http://127.0.0.1:4523/m1/4426802-0-default/',
  // baseURL: 'http://127.0.0.1:8080',
  baseURL: '/api',
  timeout: 20000,
});

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.token = userStore.token
    }
    return config;
  }, function (error) {
    return Promise.reject(error);
  });

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    const userStore = useUserStore()
    if (response.data.success === true) {
      return response
    }
    // if (response.data.msg === 'Bad credentials') {
    //   ElMessage.error('账号密码错误，请重新登录')
    // }
    if (response.data.body?.msg) {
      if (response.data.body.msg === "凭证已过期，请重新登录") {
        console.log('检测到凭证到期')
        userStore.removeToken()
        router.push('/login')
      }
    }
    console.log(response)
    ElMessage.error(response.data.msg || response.data.data || response.data.body.msg || "服务器异常1")
    return Promise.reject(response.data.body);
  },
  (error) => {
    if (error.response?.status === 401) {
      router.push('/login')
    }
    ElMessage.error(error.data.data || error || "服务器异常2") //msg改为了data
    return Promise.reject(error.data.body);
  });

export default instance;